<?php

namespace IDock\Insurance\AICS\Response;


use IDock\Http\Response;
use SimpleXMLElement;

class AllAICSResponse extends Response
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = str_replace('&lt;','<',$body);
        $body = str_replace('&gt;','>',$body);
        $body = str_replace("'",'"',$body);
        $start = strpos($body,'<response>');
        $end = strpos($body,'</response>');
        $body = substr($body,$start + 10,intval($end - $start -10));
        try {
            if ($body) {
                libxml_disable_entity_loader(false);

                $body = simplexml_load_string($body);
                $body = $this->objectToArray($body);
                $errorCode = $body['results']['responseHead']['returnCode'] ?? '';
                $message = $body['results']['responseHead']['returnMessage'] ?? '未知错误';
                $this->setBody($body);
                if ($errorCode !== 'E0000') {
                    $this->setError($message);
                    return $this;
                }
            }
        } catch (\Throwable $exception) {
            var_dump($this->getBody());
            $this->setError('AICS数据解析失败');
        }


        return $this;
    }

    protected function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    protected function errorTrans($error)
    {

    }
}
